<?php
namespace app\index\controller;

use app\common\model\Chat;
use app\common\model\Info;
use app\common\model\Qqjob;
use app\common\model\Qqs;
use app\common\model\Order;
use app\common\model\Gg;
use app\common\model\Users;
use app\common\model\Weblist;
use app\common\model\Prizes;
use think\Db;

class AdminAjax extends Ajax
{

    private $userInfo;

    public function saveWebSet()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            if (Weblist::updateByWebid($this->userInfo['web_id'], $data)) {
                $result = [
                    'code' => 0,
                    'message' => '修改信息成功'
                ];
            }
        }
        return $result;
    }

    public function config()
    {
        if (request()->isAjax()) {
            foreach (input('post.') as $k => $value) {
                $web = Weblist::where('web_id', $this->userInfo['web_id'])->find();
                Db::execute("INSERT INTO " . $web['prefix'] . "configs SET k='" . $k . "',v='" . $value . "' ON DUPLICATE KEY UPDATE v='" . $value . "'");
            }
            $result = [
                'code' => 0,
                'message' => '保存成功'
            ];
        }
        return $result;
    }

    public function count()
    {
        $result = [
            'code' => 0,
            'message' => 'success',
            'count' => [
                'user' => [
                    'all' => Users::where('web_id', '=', WEB_ID)->count('uid'),
                    'today' => Users::where('to_days(regtime) = to_days(now())')->where('web_id', WEB_ID)->count('uid')
                ],
                'qq' => [
                    'all' => Qqs::where('web_id', '=', WEB_ID)->count('qid'),
                    'today' => Qqs::where('to_days(time) = to_days(now())')->where('web_id', '=', WEB_ID)->count('qid')
                ],
                'job' => [
                    'all' => Qqjob::where('zid', '=', WEB_ID)->count('jobid'),
                ],
                'yx' => [
                    'all' => Info::allYxCount()
                ],
            ]
        ];
        return $result;
    }

    public function userList($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'login':
                    $select = Users::order('time desc')->where('web_id', '=', $this->userInfo['web_id'])->limit(20)->select();
                    foreach ($select as $row) {
                        $row['time'] = time_tran(date($row['time']));
                    }
                    $result = [
                        'code' => 0,
                        'message' => 'success',
                        'list' => $select
                    ];
                    break;
                case 'list':
                    $select = Users::search($this->userInfo['web_id']);
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
                case 'edit':
                    $data = input('post.');
                    if (!empty($data['password'])) {
                        $result = $this->validate($data, 'Users.edit');
                        if (true !== $result) {
                            $result = [
                                'code' => 0,
                                'message' => $result,
                            ];
                            return $result;
                        } else {
                            if (!empty($data['password'])) {
                                $up['password'] = make_Hash($data['password']);
                            }
                        }
                    }
                    if (!empty($data['dlpower'])) {
                        $up['dlpower'] = $data['dlpower'];
                        $up['dlzk'] = config('sys_dl_give_z_' . $data['dlpower'] . '');
                    } else {
                        $up['dlpower'] = 0;
                        $up['dlzk'] = 0;
                    }
					if($data['vipstart']==''){
						$up['vipstart'] = NULL;
					}else{
						$up['vipstart'] = $data['vipstart'];
					}
					if($data['viptime']==''){
						$up['viptime'] = NULL;
					}else{
						$up['viptime'] = $data['viptime'];
					}
					if($data['password']!==''){
						$up['password'] = make_Hash($data['password']);
					}
					$up['username'] = $data['username'];
					$up['nickname'] = $data['nickname'];
					$up['mail'] = $data['mail'];
                    $up['money'] = $data['money'];
                    $up['qq'] = $data['qq'];
					$up['jf'] = $data['jf'];
					$up['peie'] = $data['peie'];
                    if (Users::updateByUid(input('get.uid'), $up)) {
                        $result = [
                            'code' => 0,
                            'message' => '编辑用户成功',
                        ];
                    } else {
                        $result = [
                            'code' => 1,
                            'message' => '保存成功,无任何修改',
                        ];
                    }
                    break;
                case 'del':
                    $data = input('post.id');
                    if (Users::delByUid($data)) {
                        $result = [
                            'code' => 0,
                            'message' => '删除用户成功',
                        ];
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => '删除失败',
                        ];
                    }
                    break;
            }
        }
        return $result;
    }

    public function siteList($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'list':
                    $select = Weblist::search($this->userInfo['web_id']);
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
                case 'add':
                    $data = input('post.');
                    $result = Weblist::add_Web($data);
                    break;
                case 'del':
                    $id = input('post.id');
                    $data = Weblist::where('web_id', '=', $id)
                        ->find();
                    if ($id == $this->userInfo['web_id']) {
                        $result = [
                            'code' => 1,
                            'message' => '不能删除自己的站点'
                        ];
                    } elseif ($data['sup_id'] != $this->userInfo['web_id']) {
                        $result = [
                            'code' => 1,
                            'message' => '只能删除自己旗下的站点！'
                        ];
                    } else {
                        Weblist::delByid($id);
                        $result = [
                            'code' => 0,
                            'message' => '删除该分站成功！'
                        ];
                    }
                    break;
                case 'edit':
                    $id = input('web_id');
                    $data = input('post.');
                    if (Weblist::updateByWebid($id, $data)) {
                        $result = [
                            'code' => 0,
                            'message' => '编辑分站成功'
                        ];
                    } else {
                        $result['message'] = '编辑分站失败';
                    }
                    break;
            }
        }
        return $result;
    }

    public function qqList($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'today':
                    $select = Qqs::where('to_days(addtime) = to_days(now())')->where('web_id', '=', $this->userInfo['web_id'])->field('qid,qq,addtime')->select();
                    $result = [
                        'code' => 0,
                        'message' => 'success',
                        'list' => $select
                    ];
                    break;
                case 'list':
                    $select = Qqs::search();
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
                case 'del':
                    $id = input('post.qid');
                    Qqs::delByqid($id);
                    Qqjob::delByqid($id);
                    $result = [
                        'code' => 0,
                        'message' => '删除该QQ成功！'
                    ];
                    break;
            }
        }
        return $result;
    }

    public function ggList($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'add':
                    $data = input('post.');
                    $result = Gg::add($data);
                    break;
                case 'list':
                    $select = Gg::search($this->userInfo['web_id']);
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
                case 'del':
                    $id = input('post.id');
                    $data = Gg::where('id', '=', $id)
                        ->find();
                    if ($data['web_id'] != $this->userInfo['web_id']) {
                        $result = [
                            'code' => 1,
                            'message' => '只能删除自己站点的公告！'
                        ];
                    } else {
                        Gg::delByid($id);
                        $result = [
                            'code' => 0,
                            'message' => '删除该公告成功！'
                        ];
                    }
                    break;
                case 'edit':
                    $id = input('id');
                    $data = input('post.');
                    if (Gg::updateByid($id, $data)) {
                        $result = [
                            'code' => 0,
                            'message' => '编辑公告成功'
                        ];
                    } else {
                        $result['message'] = '编辑公告失败';
                    }
                    break;
            }
        }
        return $result;
    }

    public function orderList($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'list':
                    $select = Order::search($this->userInfo['web_id']);
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
            }
        }
        return $result;
    }

    public function template($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'upload':
                    $file = request()->file('f');
                    $info = $file->validate([
                        'size' => 512000,
                        'ext' => 'jpg,png,jpeg',
                        'type' => 'image/jpeg,image/png'])->move(ROOT_PATH . 'static/uploads');
                    $a = $info->getSaveName();
                    $imgp = str_replace("\\", "/", $a);
                    $imgpath = get_Domain() . 'static/uploads/' . $imgp;
                    if (!input('get.t')) {
                        Weblist::updateByWebid(WEB_ID, ['logo' => $imgpath]);
                    }
                    $result = array();
                    if ($info) {
                        $result['isSuccess'] = true;
                        $result['f'] = $imgpath;
                    } else {
                        $result['isSuccess'] = false;
                    }
                    break;
            }
        }
        return $result;
    }
	
	public function prizes($action)
    {
        if (request()->isAjax()) {
            $result = [
                'code' => -1,
                'message' => '无此操作'
            ];
            switch ($action) {
                case 'add':
                    $data = input('post.');
                    $result = Prizes::addShop($this->userInfo, $data);
                    break;
                case 'del':
                    $id = input('post.id');
                    Prizes::delShopById($id);
                    $result = [
                        'code' => 0,
                        'message' => '删除奖品成功！'
                    ];
                    break;
                case 'list':
                    $select = Prizes::search($this->userInfo['web_id']);
                    if (false === $select) {
                        $result['message'] = '获取列表失败，请稍后再试';
                    } elseif (is_string($select)) {
                        $result['message'] = $select;
                    } else {
                        $result = [
                            'code' => 0,
                            'message' => 'success',
                            'total' => $select['total'],
                            'list' => $select['list']
                        ];
                    }
                    break;
            }
        }
        return $result;
    }

    public function testSendMail()
    {
        $send_mail = input('post.mail');
        if (!config('sys_mail_pwd') || !config('sys_mail_name') || !config('sys_mail_port') || !config('sys_mail_smtp')) {
            $result = [
                'code' => 0,
                'message' => '请先配置好邮箱信息，再测试发信！'
            ];
        } else if (!check_mail($send_mail)) {
            $result = [
                'code' => 0,
                'message' => '邮箱格式不正确！'
            ];
        } else {
            $send_result = send_mail($send_mail, config('web_webname') . '- 测试发信', '当你收到这封邮件，证明您的邮箱配置已成功。');
            if ($send_result) {
                $result = [
                    'code' => 1,
                    'message' => '您的邮箱：' . $send_mail . '将会收到一份邮件,如果没有收到邮件就是配置失败了，请仔细检查您的配置信息再试！'
                ];
            } else {
                $result = [
                    'code' => 1,
                    'message' => '您的邮箱：' . $send_mail . '将会收到一份邮件,如果没有收到邮件就是配置失败了，请仔细检查您的配置信息再试！'
                ];
            }
        }
        return $result;
    }
	
	public function CloudShop()
    {
        if (request()->isAjax()) {
            $result = '<title>应用商店</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="hei">应用商店</p><p class="hui mt5 pb9">应用商店可在线在云端下载或购买你想要的模板或插件,如网站功能,挂机功能,代挂功能,首页模板等,支持一键下载到本地,预计在1.1.0以上版本上线,敬请期待</p><p class="lv mt5 pb9">关注版本后续请加入: <a href="https://jq.qq.com/?_wv=1027&k=5e3pBAP">QQ交流群</a></p></span> </div>
						</div>';
        }
        echo $result;
    }

    public function zipExtract($src, $dest)
    {
        $zip = new \ZipArchive();
        if ($zip->open($src) === true) {
            $zip->extractTo($dest);
            $zip->close();
            return true;
        }
        return false;
    }
	
	public function siteLog()
    {
			$yxnum = Info::where(['sysid' => 0])->find();
			$data =
                [
                    'code' => 0,
                    'start_time' => Weblist::start_Time(),
                    'end_time' => Weblist::end_Time(),
                    'operating_system' => PHP_OS,
                    'runtime_environment' => $_SERVER["SERVER_SOFTWARE"],
                    'operation_mode' => php_sapi_name(),
                    'thinkphp_version' => THINK_VERSION . '',
                    'execution_time_limit' => ini_get('max_execution_time') . '秒',    // 执行时间限制
                    'server_time' => date("Y年n月j日 H:i:s"),    // 服务器时间
                    'server_domain_name' => $_SERVER['SERVER_NAME'] . ' （' . get_ip_city($_SERVER['SERVER_NAME']) . '）',
                    'free_space' => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
                    'cron_task' => Qqjob::where('zid', '=', WEB_ID)->count(),
                    'site_info' => $yxnum['times'],
                    'site_last' => $yxnum['last'],
                ];
			$result = '<title>服务器信息</title>
					<div class="g-content in-list in-p in-b" id="qdlistbody">
					<dl>
						<dd><p class="f5 hui">网站已安全运行</dd>
						<dt class="t-r"><p class="lv bold">'.$data['start_time'].'天</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">站点到期时间</dd>
						<dt class="t-r"><p class="lv bold">'.config('web_end_time').'</p><p class="f3 hui">还有'.$data['end_time'].'天到期</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">系统版本号</dd>
						<dt class="t-r"><p class="lv bold">'.config('version.versionName').'</p><p class="f3 hui">版本号:'.config('version.versionCode').'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">Thinkphp框架版本</dd>
						<dt class="t-r"><p class="lv bold">'.$data['thinkphp_version'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">服务器时间</dd>
						<dt class="t-r"><p class="lv bold">'.$data['server_time'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">服务器操作系统</dd>
						<dt class="t-r"><p class="lv bold">'.$data['operating_system'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">PHP运行方式</dd>
						<dt class="t-r"><p class="lv bold">'.$data['operation_mode'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">服务器剩余硬盘</dd>
						<dt class="t-r"><p class="lv bold">'.$data['free_space'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">服务器物理地址</dd>
						<dt class="t-r"><p class="lv bold">'.$data['server_domain_name'].'</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">系统挂机任务数</dd>
						<dt class="t-r"><p class="lv bold">'.$data['cron_task'].'条任务</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">系统已运行次数</dd>
						<dt class="t-r"><p class="lv bold">'.$data['site_info'].'次</p></dt>
					</dl>
					<dl>
						<dd><p class="f5 hui">上次执行时间</dd>
						<dt class="t-r"><p class="lv bold">'.$data['site_last'].'</p></dt>
					</dl>
					</div>';
        echo $result;
    }

    public function is_update()
    {
			$web_cofig = Db::name('weblist')
			->where('web_id', '=', 1)
			->find();
            $version = config('version');
            $api = send_get('https://www.emapi.cn/api/GetUpdate/Action/check?code=5e9ff9e35a627&version=' . $version['versionCode'] . '&domain='. $web_cofig['domain']);
            $json=json_decode($api, true);
            if($json['code']=='-1'){
	        	$result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-info f16 hong"></i></p><p class="hei">检测失败</p><p class="hui mt5 pb9">你的域名验证未通过,请联系开发者添加白名单</p></span> </div>
						</div>';
        	}elseif($json['code']=='-4'){
	        	$result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-info f16 hong"></i></p><p class="hei">检测失败</p><p class="hui mt5 pb9">你的域名验证未通过,请联系开发者添加白名单</p></span> </div>
						</div>';
        	}elseif ($json['code'] == 0) {
                $result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-check f16 lv"></i></p><p class="hei">检测成功</p><p class="hui mt5 pb9">你当前已经是最新版的织音QQ助手了</p></span> </div>
						</div>';
            } elseif ($json['code'] == 1) {
				$result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-check f16 qing"></i></p><p class="hei">检测成功</p><p class="hui mt5 pb9">检测到新版本:' . $json['version'] . '</p>
							<a class="btn btn-qing btn-block rx1" onclick="updates(\'' . $json['zip'] . '\',\'' . $json['version'] . '\')">升級到新版本</a>
							</span> </div>
						</div>
				<script> function updates(url,version) {
                layer.msg("正在更新系统...", {icon: 16,time: 1000}, function(){
				app.ajax(\''. url('admin_ajax/update') .'\', {url: url,version: version}, function (d) {
                    if (d.code == 0) {
                        layer.msg(d.message, {icon: 6,time: 1000});
                    } else {
                        layer.msg(d.message, {icon: 5,time: 1000});
                    }
                }, \'\', false);
            });
                
            }</script>';
            } elseif ($json['code'] == '-3') {
                $result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-info f16 hong"></i></p><p class="hei">检测失败</p><p class="hui mt5 pb9">你当前使用的版本号不正确</p></span> </div>
						</div>';
            } elseif ($json == NULL) {
                $result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-info f16 hong"></i></p><p class="hei">检测失败</p><p class="hui mt5 pb9">本次检测发生未知错误</p></span> </div>
						</div>';
            } else {
				$result = '<title>更新检测
							<a class="btn btn-sm btn-cheng btn-1 rx1 bold ml8" href="http://blog.wmza.cn/index.php/archives/31">更新记录</a>
						</title>
						<div class="p6 t-c">
							<div class="pt4 pb4 f5 bold lv"><span><p class="mt5"><i class="icon icon-info f16 hong"></i></p><p class="hei">检测失败</p><p class="hui mt5 pb9">本次检测发生未知错误</p></span> </div>
						</div>';
			}
        echo $result;
    }

    public function update()
    {
        $url = input('post.url');
		$version = input('post.version');
        $file = 'update.zip';
        copy($url, $file) || $result = ['code' => 1, 'message' => '无法下载更新包文件！'];
        if ($this->zipExtract($file, $_SERVER['DOCUMENT_ROOT'])) {
            $filename = 'https://www.emapi.cn/update/5e9ff9e35a627/'.$version.'/update.sql';
			$headers = get_headers($filename);
		if (!strpos($headers[0], '404')) {
            if ($sqls = file_get_contents($filename)) {
                $sqls = explode(';', $sqls);
                foreach ($sqls as $value) {
                    $value = trim($value);
                    if (!empty($value)) {
                        Db::execute($value);
                    }
                }
                $result = [
                    'code' => 0,
                    'message' => '系统更新成功，SQL数据写入成功'
                ];
            } else {
                $result = [
                    'code' => 0,
                    'message' => '系统更新成功'
                ];
            }
		}else{
			$result = [
                    'code' => 0,
                    'message' => '系统更新成功'
                ];
		}
            unlink($file);
        } else {
            $result = [
                'code' => 0,
                'message' => '无法解压更新包文件！'
            ];
            if (file_exists($file)) unlink($file);
        }
        return $result;
    }

    protected
    function _initialize()
    {
        parent::_initialize();
        $this->checkLogin();
		if(check_mobile()){
			header('Location: '.url('mobile/index').'');
			exit;
		}
		
    }
	
	private
    function checkLogin()
    {
        $check_Login = Users::checkLogin();
        if ($check_Login != null) {
            $this->assign('alert', $check_Login['msg']);
            $this->assign('url', $check_Login['url']);
            exit($this->fetch('pc/common/msg'));
        } else {
            $this->userInfo = Users::getLoginUser();
            $this->assign('userInfo', $this->userInfo);

        }
    }
}